package com.petdog.module.community.controller;

import com.petdog.common.dto.ApiResponse;
import com.petdog.common.dto.PageResult;
import com.petdog.module.community.dto.PostCreateRequest;
import com.petdog.module.community.dto.PostUpdateRequest;
import com.petdog.module.community.dto.PostDetailResponse;
import com.petdog.module.community.dto.PostListResponse;
import com.petdog.module.community.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 帖子控制器
 */
@RestController
@RequestMapping("/api/posts")
public class PostController {
    
    @Autowired
    private PostService postService;
    
    /**
     * 创建帖子
     */
    @PostMapping
    public ApiResponse<Long> createPost(@RequestBody PostCreateRequest request) {
        try {
            // 参数校验
            if (request.getContent() == null || request.getContent().isEmpty()) {
                return ApiResponse.error("内容不能为空");
            }
            
            if (request.getContent().length() > 500) {
                return ApiResponse.error("内容不能超过500个字符");
            }
            
            // 检查是否选择了媒体类型
            if (request.getType() != null) {
                if (request.getType() == 1 && (request.getImageUrls() == null || request.getImageUrls().isEmpty())) {
                    return ApiResponse.error("请上传至少一张图片");
                }
                if (request.getType() == 2 && (request.getVideoUrl() == null || request.getVideoUrl().isEmpty())) {
                    return ApiResponse.error("请上传视频");
                }
            }
            
            Long postId = postService.createPost(request);
            return ApiResponse.success(postId);
        } catch (RuntimeException e) {
            if (e.getMessage().contains("用户未加入该社区")) {
                return ApiResponse.error("需先加入该社区才能发布动态");
            } else if (e.getMessage().contains("违规信息")) {
                return ApiResponse.error("发布内容含违规信息，请修改后重新提交");
            }
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 更新帖子
     */
    @PutMapping
    public ApiResponse<Boolean> updatePost(@RequestBody PostUpdateRequest request) {
        boolean success = postService.updatePost(request);
        return success ? ApiResponse.success(true) : ApiResponse.error("更新失败，您可能没有权限更新此帖子");
    }
    
    /**
     * 删除帖子
     */
    @DeleteMapping("/{postId}")
    public ApiResponse<Boolean> deletePost(@PathVariable Long postId, @RequestParam Long userId) {
        boolean success = postService.deletePost(postId, userId);
        return success ? ApiResponse.success(true) : ApiResponse.error("删除失败，您可能没有权限删除此帖子");
    }
    
    /**
     * 查询帖子详情
     */
    @GetMapping("/{postId}")
    public ApiResponse<PostDetailResponse> getPostDetail(@PathVariable Long postId) {
        PostDetailResponse post = postService.getPostDetail(postId);
        return post != null ? ApiResponse.success(post) : ApiResponse.error("帖子不存在");
    }
    
    /**
     * 获取社区动态流
     * 支持游标分页、下拉刷新和上拉加载更多
     */
    @GetMapping("/community/{communityId}")
    public ApiResponse<List<PostListResponse>> getCommunityPosts(
            @PathVariable Long communityId,
            @RequestParam Map<String, Object> params) {
        try {
            params.put("communityId", communityId);
            
            // 确保有分页参数
            if (!params.containsKey("pageSize")) {
                params.put("pageSize", 20); // 默认每页20条
            }
            
            // 支持游标分页（通过最后一条记录的ID进行分页）
            if (params.containsKey("lastPostId")) {
                Long lastPostId = Long.valueOf(params.get("lastPostId").toString());
                params.put("lastPostId", lastPostId);
            }
            
            List<PostListResponse> posts = postService.getCommunityPosts(params);
            return ApiResponse.success(posts);
        } catch (Exception e) {
            return ApiResponse.error("动态加载失败，请点击重试");
        }
    }
    
    /**
     * 获取社区动态流 - 符合需求文档的接口规范
     */
    @GetMapping("/communities/{communityId}/posts")
    public ApiResponse<List<PostListResponse>> getCommunityDynamicStream(
            @PathVariable Long communityId,
            @RequestParam(required = false) Long lastPostId,  // 游标分页参数
            @RequestParam(defaultValue = "20") int pageSize) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("communityId", communityId);
            params.put("pageSize", pageSize);
            
            if (lastPostId != null && lastPostId > 0) {
                params.put("lastPostId", lastPostId);
            }
            
            List<PostListResponse> posts = postService.getCommunityPosts(params);
            return ApiResponse.success(posts);
        } catch (Exception e) {
            return ApiResponse.error("动态加载失败，请点击重试");
        }
    }
    
    /**
     * 获取用户发布的帖子
     */
    @GetMapping("/user/{userId}")
    public ApiResponse<List<PostListResponse>> getUserPosts(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int pageSize) {
        List<PostListResponse> posts = postService.getUserPosts(userId, page, pageSize);
        return ApiResponse.success(posts);
    }
    
    /**
     * 点赞帖子
     */
    @PostMapping("/{postId}/like")
    public ApiResponse<Boolean> likePost(@PathVariable Long postId, @RequestParam Long userId) {
        boolean success = postService.likePost(postId, userId);
        return success ? ApiResponse.success(true) : ApiResponse.error("点赞失败");
    }
    
    /**
     * 取消点赞帖子
     */
    @DeleteMapping("/{postId}/like")
    public ApiResponse<Boolean> unlikePost(@PathVariable Long postId, @RequestParam Long userId) {
        boolean success = postService.unlikePost(postId, userId);
        return success ? ApiResponse.success(true) : ApiResponse.error("取消点赞失败");
    }
    
    /**
     * 检查用户是否已点赞帖子
     */
    @GetMapping("/{postId}/like-check")
    public ApiResponse<Boolean> isUserLikedPost(@PathVariable Long postId, @RequestParam Long userId) {
        boolean isLiked = postService.isUserLikedPost(postId, userId);
        return ApiResponse.success(isLiked);
    }
}